package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.po.Book;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.mapper.FavoriteMapper;
import com.it.schoolbookshop_back.service.FavoriteService;
import com.it.schoolbookshop_back.service.BookService;
import com.it.schoolbookshop_back.service.NotificationService;
import com.it.schoolbookshop_back.service.UserService;
import com.it.schoolbookshop_back.enums.NotificationType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Date;

/**
 * 收藏服务实现类
 */
@Service
public class FavoriteServiceImpl implements FavoriteService {

    private final FavoriteMapper favoriteMapper;
    private final BookService bookService;
    private final NotificationService notificationService;
    private final UserService userService;

    @Autowired
    public FavoriteServiceImpl(FavoriteMapper favoriteMapper, BookService bookService, NotificationService notificationService, UserService userService) {
        this.favoriteMapper = favoriteMapper;
        this.bookService = bookService;
        this.notificationService = notificationService;
        this.userService = userService;
    }

    @Override
    @Transactional
    public boolean addFavorite(Integer userId, Integer bookId) throws IllegalArgumentException {
        // 检查书籍是否可收藏（存在且状态为active）
        if (!favoriteMapper.checkBookFavoritable(bookId)) {
            throw new IllegalArgumentException("书籍不存在或已下架");
        }
        
        // 检查是否已收藏
        Integer favoriteId = favoriteMapper.checkFavorite(userId, bookId);
        if (favoriteId != null) {
            throw new IllegalArgumentException("您已收藏过此书");
        }
        
        // 添加收藏
        int result = favoriteMapper.addFavorite(userId, bookId);
        
        // 更新用户收藏数量
        if (result > 0) {
            favoriteMapper.increaseFavoriteCount(userId);
            System.out.println("用户 " + userId + " 收藏了书籍 " + bookId + "，收藏量+1");
        }
        
        return result > 0;
    }
    
    @Override
    @Transactional
    public boolean cancelFavorite(Integer userId, Integer bookId) throws IllegalArgumentException {
        // 检查是否已收藏
        Integer favoriteId = favoriteMapper.checkFavorite(userId, bookId);
        if (favoriteId == null) {
            throw new IllegalArgumentException("您尚未收藏此书");
        }
        
        // 取消收藏
        int result = favoriteMapper.cancelFavorite(userId, bookId);
        
        // 更新用户收藏数量
        if (result > 0) {
            favoriteMapper.decreaseFavoriteCount(userId);
            System.out.println("用户 " + userId + " 取消收藏书籍 " + bookId + "，收藏量-1");
        }
        
        return result > 0;
    }
    
    @Override
    @Transactional
    public FavoriteToggleResult toggleFavorite(Integer userId, Integer bookId) {
        // 验证参数
        if (userId == null || bookId == null) {
            throw new IllegalArgumentException("用户ID和书籍ID不能为空");
        }
        
        // 验证书籍是否存在
        Book book = bookService.getBookById(bookId);
        if (book == null) {
            throw new IllegalArgumentException("书籍不存在");
        }
        
        // 查询当前收藏状态
        Integer favoriteId = favoriteMapper.checkFavorite(userId, bookId);
        
        boolean isAdded = false;
        boolean success = false;
        
        if (favoriteId == null) {
            // 未收藏，添加收藏
            int result = favoriteMapper.addFavorite(userId, bookId);
            success = result > 0;
            isAdded = true;
            
            // 如果添加收藏成功，则创建通知
            if (success) {
                // 获取卖家ID
                Integer sellerId = book.getSellerId();
                
                // 不要给自己发送通知
                if (!userId.equals(sellerId)) {
                    // 获取收藏者用户信息
                    User user = userService.getUserById(userId);
                    String username = user != null ? user.getUsername() : "未知用户";
                    
                    // 构建更详细的通知内容，包含用户名
                    String content = "用户 " + username + " 收藏了您的书籍《" + book.getTitle() + "》";
                    
                    // 创建通知并保存到数据库
                    notificationService.createNotification(
                        sellerId,                  // 卖家ID
                        NotificationType.FAVORITE, // 通知类型
                        content,                   // 通知内容，现在包含用户名
                        bookId                     // 相关书籍ID
                    );
                    
                    // 添加调试日志
                    System.out.println("创建收藏通知: 用户 " + username + " 收藏了 " + sellerId + " 的书籍《" + book.getTitle() + "》");
                }
            }
        } else {
            // 已收藏，取消收藏
            int result = favoriteMapper.cancelFavorite(userId, bookId);
            success = result > 0;
            isAdded = false;
        }
        
        // 更新用户收藏计数
        if (isAdded) {
            favoriteMapper.increaseFavoriteCount(userId);
        } else {
            favoriteMapper.decreaseFavoriteCount(userId);
        }
        
        return new FavoriteToggleResult(success, isAdded);
    }
    
    @Override
    public List<Book> getFavoriteBooks(Integer userId) {
        List<Book> books = favoriteMapper.getFavoriteBooks(userId);
        
        // 记录日志
        System.out.println("\n====== 查询用户收藏的书籍 ======");
        System.out.println("用户ID: " + userId);
        System.out.println("收藏书籍数量: " + books.size());
        
        // 输出前几本书的基本信息（方便调试）
        int count = 0;
        for (Book book : books) {
            System.out.println("- " + book.getId() + ": " + book.getTitle() + 
                              ", 价格: " + book.getPrice() + 
                              ", 状态: " + book.getStatus());
            
            // 只打印前5本，避免日志过多
            if (++count >= 5 && books.size() > 5) {
                System.out.println("... 以及其他 " + (books.size() - 5) + " 本书");
                break;
            }
        }
        System.out.println("====== 查询用户收藏的书籍结束 ======\n");
        
        return books;
    }
    
    @Override
    public Integer getFavoriteId(Integer userId, Integer bookId) {
        // 调用mapper层方法检查收藏关系并获取ID
        return favoriteMapper.checkFavorite(userId, bookId);
    }
} 